import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:untitled/dao/dart_api.dart';

class LineDetailWidget extends StatefulWidget {
  const LineDetailWidget(
      {super.key,
      required this.busLineName,
      required this.localStationName,
      required this.typeOfVehicle});

  final String busLineName;
  final String localStationName;
  final String typeOfVehicle; //交通工具类型

  @override
  // ignore: no_logic_in_create_state
  State<LineDetailWidget> createState() =>
      // ignore: no_logic_in_create_state
      _LineDetailWidgetState(
          lineName: busLineName,
          localStationName: localStationName,
          typeOfVehicle: typeOfVehicle);
}

class _LineDetailWidgetState extends State<LineDetailWidget> {
  _LineDetailWidgetState(
      {required this.localStationName,
      required this.typeOfVehicle,
      required this.lineName}); // 接受参数
  final String lineName;
  final String typeOfVehicle; //交通工具类型
  final String localStationName;
  List<dynamic> stationData = [];
  double stationProgressBarWidth = 100;
  final ScrollController _scrollController = ScrollController(); //设置初始滚动位置
  String tagName = ""; //公交名称

  @override
  void initState() {
    super.initState();
    switch (typeOfVehicle) {
      case "busSite":
        {
          if (lineName.contains("000")) {
            tagName = "${lineName.split("000")[0]}路" +
                (lineName.split("000")[1] == 1 ? "A" : "B");
          } else {
            tagName = "$lineName路";
          }
          findBusLine(lineName);
        }
        break;
      case "subway":
        {
          tagName = "$lineName号线";
          findSubwayLine(lineName);
        }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0, 5, 0, 0),
      child: Container(
        padding: const EdgeInsets.fromLTRB(10, 10, 10, 10),
        decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(5))),
        width: 110,
        height: 110,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              flex: 3,
              child: Padding(
                  padding: const EdgeInsets.fromLTRB(0, 5, 0, 5),
                  child: Container(
                    width: 100,
                    height: 100,
                    child: Stack(
                      alignment: Alignment.bottomCenter,
                      children: [
                        Container(
                          width: 80,
                          height: 80,
                          decoration: const BoxDecoration(
                            color: Color.fromARGB(255, 240, 240, 240),
                            shape: BoxShape.circle,
                          ),
                          child: Padding(
                            padding: const EdgeInsets.all(12),
                            child: _getDetailLineIcon(typeOfVehicle),
                          ),
                        ),
                        Container(
                          padding: const EdgeInsets.fromLTRB(10, 5, 10, 5),
                          decoration: const BoxDecoration(
                              color: Colors.black45,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(30))),
                          child: Text(
                            tagName,
                            style: const TextStyle(
                              color: Colors.white,
                              fontSize: 12,
                            ),
                          ),
                        ),
                      ],
                    ),
                  )),
            ),
            Expanded(
                flex: 7,
                child: ListView(
                  controller: _scrollController,
                  scrollDirection: Axis.horizontal,
                  children: <Widget>[
                    SizedBox(
                      width: stationProgressBarWidth, // 设置适当的宽度
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: _loadStationWidget(),
                          ),
                          const SizedBox(height: 10),
                          // Add spacing between station names and progress bar
                          LinearProgressIndicator(
                            value: 0.5,
                            // Update this value dynamically based on bus position
                            minHeight: 5,
                            backgroundColor: Colors.grey[200]!,
                            color: Colors.blue[300]!,
                            valueColor:
                                const AlwaysStoppedAnimation(Colors.blue),
                          ),
                        ],
                      ),
                    ),
                  ],
                ))
          ],
        ),
      ),
    );
  }

  //加载公交的具体信息
  findBusLine(line) async {
    List<dynamic> resData = await DartAPI.findAllBusLine(line);
    try {
      resData.sort((a, b) => (a["sort"] as int).compareTo(b["sort"] as int));
    } catch (_) {
      print("异常：                              $resData");
    }
    //更新界面
    setState(() {
      stationData = resData;
      stationProgressBarWidth = stationData.length * 100;
      int localFlag = 0;
      for (var element in stationData) {
        if (element['station_Name'] == localStationName) break;
        localFlag++;
      }
      _scrollController.animateTo(localFlag * 100,
          duration: const Duration(milliseconds: 300), curve: Curves.easeInOut);
    });
  }

  //加载地铁的具体站点信息
  findSubwayLine(line) async {
    List<dynamic> resData = await DartAPI.findAllSubwayByLine(line);
    try {
      resData.sort((a, b) =>
          (a["down_ordinal"] as int).compareTo(b["down_ordinal"] as int));
    } catch (_) {
      print("异常：                              $resData");
    }
//更新界面
    setState(() {
      stationData = resData;
      stationProgressBarWidth = stationData.length * 100;
      int localFlag = 0;
      for (var element in stationData) {
        if (element['station_name'] == localStationName) break;
        localFlag++;
      }
      _scrollController.animateTo(localFlag * 100,
          duration: const Duration(milliseconds: 300), curve: Curves.easeInOut);
    });
  }

  _loadStationWidget() {
    List<Widget> widgets = [];
    String nameTag = "";
    if (typeOfVehicle == 'busSite') {
      nameTag = "station_Name";
    }
    if (typeOfVehicle == 'subway') {
      nameTag = "station_name";
    }
    for (var element in stationData) {
      final GlobalKey globalKey = GlobalKey();

      Center container = Center(
        child: SizedBox(
          width: 100,
          key: globalKey,
          child: Column(
            children: [
              Text(
                element[nameTag],
                overflow: TextOverflow.ellipsis,
              ),
              const Icon(
                Icons.directions_bus_filled,
                size: 14,
                color: Colors.black45,
              )
            ],
          ),
        ),
      );
      widgets.add(container);
    }

    return widgets;
  }

  _getDetailLineIcon(String typeOfVehicle) {
    switch (typeOfVehicle) {
      case 'busSite':
        return Image.asset(
            "assets/img/icon/tool/icon_bus_selected.png");
      case 'subway':
        return Image.asset(
            "assets/img/icon/tool/icon_subway_selected.png");
    }
  }
}
